from moodlefuse.parsers import Parser
from moodlefuse.files import FileSource
from files import Resource
import re
from posixpath import basename
from urlparse import urlparse
from moodlefuse.settings import MOODLE_WEBSITE_URL

class ResourcesParser(Parser):

    def parse_resources(self):
        soup = self.get_parsed_data()
        regex = re.compile('resource/view\.php\?id=\d+')
        resources_html = soup.findAll('a', attrs={'href':regex})

        resources = {}
        for resource_html in resources_html:
            try:
                name, url = self.parse_resource_info(resource_html['href'])
            except ResourcesParser.NotFileResource:
                #TODO read html and convert to pdf?
                continue

            resource = Resource(self.api, name, url, source=FileSource.DOWNLOADED)
            resources[resource.name] = resource

        return resources

    def parse_resource_name(self, html):
        return html.text.encode('utf-8')

    def force_showing_actual_url(self, url):
        return url + '&inpopup=true'

    def parse_resource_info(self, url):
        url         = self.force_showing_actual_url(url)

        if MOODLE_WEBSITE_URL not in url:
            raise ResourcesParser.NotFileResource("%s is not a right file" % url)

        try:
            response    = self.browser.open(url)
            headers     = response.info()
            url         = response.geturl()

            # use only resources stored on moodle
            if MOODLE_WEBSITE_URL not in url or 'text/html' in headers['content-type']:
                raise ResourcesParser.NotFileResource("%s is not a right file" % url)

            name = basename(urlparse(url).path).encode('utf-8')

            return name, url
        except:
            raise ResourcesParser.NotFileResource("%s is not a file" % url)

    class NotFileResource(Exception):
        def __init__(self, value):
            self.value = value
        def __str__(self):
            return repr(self.value)
        

        

  